package com.np.adapterdemo2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.np.adapterdemo2.pojo.Blog;

import java.util.ArrayList;
import java.util.List;

public class RecyclerViewActivity extends AppCompatActivity {

    private static final String TAG = BaseAdapterNoLayoutActivity.class.getSimpleName();
    private List<Blog> mBlogList = new ArrayList<>();
    private BlogAdapter mAdapter;
    private RecyclerView mRecyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view);

        mRecyclerView = findViewById(R.id.recyclerview1);

        // 模拟数据
        for (int i = 0; i < 50; i++) {
            Blog blog = new Blog();
            blog.setTitle("标题" + i);
            blog.setContent("内容" + i);
            mBlogList.add(blog);
        }

        mAdapter = new BlogAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
    }

    class BlogViewHolder extends RecyclerView.ViewHolder {
        TextView tvTitle;
        Button buttonSelect;

        public BlogViewHolder(@NonNull View v) {
            super(v);
            tvTitle = v.findViewById(R.id.tv_title);
            buttonSelect = v.findViewById(R.id.button_select);
        }
    }

    class BlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
        @NonNull
        @Override
        public BlogViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //View view = View.inflate(RecyclerViewActivity.this, R.layout.item_blog, null);    // 这样写子组件都挤到左边了
            View view = LayoutInflater.from(RecyclerViewActivity.this).inflate(R.layout.item_blog, parent, false);
            BlogViewHolder viewHolder = new BlogViewHolder(view);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull BlogViewHolder holder, int position) {
            Blog blog = mBlogList.get(position);

            holder.tvTitle.setText(blog.getTitle());
            holder.buttonSelect.setOnClickListener(v -> {
                getIntent().putExtra("entity", blog);
                setResult(Activity.RESULT_OK, getIntent());
                finish();
            });
        }

        @Override
        public int getItemCount() {
            return mBlogList.size();
        }
    }
}